<script setup lang="ts">
import type { ToolInstallVersionItem } from "@/pages/tools/common/types";
import { type PropType, ref, shallowRef } from "vue";
import { getPythonDownloadFilesFromHuaweiCloud, getPythonDownloadFilesFromNpmmirror, getPythonDownloadFilesFromOfficial } from "./py-api";
import { message } from "ant-design-vue";
import { usePythonStore } from "@/pages/tools/python/py-store";
import { openExternal } from "@/framework/util/shell";

defineOptions({ name: "py-install-operation" });
const props = defineProps({
  versionInfo: { type: Object as PropType<ToolInstallVersionItem>, required: true },
  mirror: { type: String as PropType<keyof typeof apis>, required: true },
});

const pythonStore = usePythonStore();
const apis = {
  npmmirror: getPythonDownloadFilesFromNpmmirror,
  huaweicloud: getPythonDownloadFilesFromHuaweiCloud,
  official: getPythonDownloadFilesFromOfficial,
};

const versions = shallowRef<ToolInstallVersionItem[]>([]);
const versionsLoading = ref(false);
const downloadListModalOpen = ref(false);

async function getDownloadList() {
  versionsLoading.value = true;
  try {
    const { version } = props.versionInfo!;
    const downloadFiles = await apis[props.mirror]?.(version);
    if (downloadFiles == undefined || downloadFiles.length == 0) {
      message.error("该版本没有安装文件");
      pythonStore.setNonInstallerVersion(version, true);
      return;
    }
    versions.value = downloadFiles;
  } catch (e: any) {
    console.error(e);
    message.error(e.message);
  } finally {
    versionsLoading.value = false;
  }

  downloadListModalOpen.value = true;
  console.log(versions.value);
}
</script>

<template>
  <a-button size="small" type="text" :loading="versionsLoading" @click="getDownloadList">下载</a-button>
  <a-modal v-model:open="downloadListModalOpen" title="下载列表" width="700px" centered destroy-on-close>
    <template v-for="it in versions" :key="it.id">
      <div class="tool-install-version-item">
        <a-space>
          <span class="hover-underline" @click="openExternal(it.url)">{{ it.name }}</span>
          <span class="color-text-secondary">{{ it.modified?.toLocaleString() }}</span>
        </a-space>
      </div>
    </template>
  </a-modal>
</template>

<style scoped lang="less"></style>
